package com.vcc.msc.sbs.proxy;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.vcc.msc.sbs.common.RequestMethodType;
import com.vcc.msc.sbs.entity.WesEntity;

public class WesProxyService extends RESTClientProxyService implements WesProxy {

	private static WesProxyService instance = null;

	private WesProxyService() {
		super();
	}

	public static WesProxyService getInstance() {
		if (instance == null) {
			instance = new WesProxyService();
		}
		return instance;
	}

	public WesEntity getWesDetails(String version, String typeCode, String wesId) {
		return null;
	}

	public List<String> getWesIds(String typeCode) {
		return null;
	}

	public boolean addWesImage() {
		// TODO handle the buildId? in server side

		return true;
	}

	public boolean updateWes() {
		return true;
	}

	public boolean sendPdf() {
		return true;
	}

	public byte[] getWesImage() {
		Log.d(this.getClass().getName(), "Before Connection");

		byte[] image = null;
		try {
			image = downloadImage(GET_WES_IMAGE, RequestMethodType.GET);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}

	private byte[] downloadImage(String methodName, RequestMethodType methodType)
			throws Exception {
		byte[] image = null;

		// add parameters
		String combinedParams = "";
		if (!params.isEmpty()) {
			combinedParams += "?";
			for (NameValuePair p : params) {
				String paramString = p.getName() + "="
						+ URLEncoder.encode(p.getValue(), "UTF-8");
				if (combinedParams.length() > 1) {
					combinedParams += "&" + paramString;
				} else {
					combinedParams += paramString;
				}
			}
		}

		String getUrl = WEBSERVICE_URL + methodName + combinedParams;
		HttpGet request = new HttpGet(getUrl);
		Log.d(RESTClientProxyService.class.toString(), getUrl);

		// add headers
		for (NameValuePair h : headers) {
			request.addHeader(h.getName(), h.getValue());
		}
		image = callWebService(request);
		cleanup();
		return image;
	}

	private byte[] callWebService(HttpUriRequest request) {

		HttpClient httpclient = new DefaultHttpClient();
		byte[] image = null;

		try {
			HttpResponse response = httpclient.execute(request);

			StatusLine statusLine = response.getStatusLine();
			statusCode = statusLine.getStatusCode();
			errorMessage = statusLine.getReasonPhrase();

			if (statusCode == REST_RESPONSE_OK) {
				HttpEntity entity = response.getEntity();
				InputStream instream = entity.getContent();

				image = convertStreamToByteCode(instream);

				// Closing the input stream will trigger connection release
				instream.close();
			} else {
				Log.e(this.getClass().getName(), "Failed to download file");
			}
			Log.d(this.getClass().getName(), "After Connection");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	private byte[] convertStreamToByteCode(InputStream instream)
			throws IOException {

		ByteArrayOutputStream buffer = new ByteArrayOutputStream();

		int nRead;
		byte[] data = new byte[16384];

		while ((nRead = instream.read(data, 0, data.length)) != -1) {
			buffer.write(data, 0, nRead);
		}

		buffer.flush();

		return buffer.toByteArray();

	}

	@Override
	public List<WesEntity> getWesList(String version, String typeCode,
			String wesNo) {
		// TODO Auto-generated method stub
		return null;
	}

}
